package server

import (
	"fmt"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"log"
	"net"
	"serve/settings"
	"serve/shared/antu/auth"
)

type GrpcConfig struct {
	Name              string
	Addr              int
	AuthPublicKeyFile string
	RegisterFunc      func(server *grpc.Server)
	Logger            *zap.Logger
}

func RunGRPCServer(c *GrpcConfig) error {
	err := settings.Init()
	if err != nil {
		log.Fatalf("settings.Init() %v", err)
	}

	nameField := zap.String("name", c.Name)
	listen, err := net.Listen("tcp", fmt.Sprintf(":%d", c.Addr))
	if err != nil {
		c.Logger.Fatal("cannot listen err", nameField, zap.Error(err))
	}

	var opts []grpc.ServerOption

	if c.AuthPublicKeyFile != "" {
		interceptor, err := auth.Interceptor(c.AuthPublicKeyFile) // 这儿主要是封装了一个context
		if err != nil {
			c.Logger.Fatal("auth.Interceptor(\"shared/auth/public.key\") err", nameField, zap.Error(err))
		}
		opts = append(opts, grpc.UnaryInterceptor(interceptor))
	}

	s := grpc.NewServer(opts...) // 新建一个grpcServer
	c.RegisterFunc(s)
	c.Logger.Info("grpc server started ", nameField, zap.Int("addr:", c.Addr))
	return s.Serve(listen) // 启动
}
